from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import *
from .ser import *


# Create your views here.


class UserM(APIView):
    def get(self, request):
        user = User.objects.all()
        ser = UserSer(user, many=True)
        return Response({'code': 200, 'list': ser.data})


class ShopM(APIView):
    def get(self, request):
        shop = Shop.objects.all()
        ser = ShopSer(shop, many=True)
        return Response({'code': 200, 'list': ser.data})

    def delete(self, request):
        id = request.GET.get('id')
        Shop.objects.filter(id=id).delete()
        return Response({'code': 200})


class LoginM(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = User.objects.filter(username=username).first()
        if username == username:
            return Response({'code': 200, 'userid': user.id})
        else:
            return Response({'code': 20010})


class StuM(APIView):
    def get(self, request):
        id = request.GET.get('id')
        if not id:
            stu = KeCheng.objects.all()
            ser = KecSer(stu, many=True)
            return Response({'code': 200, 'list': ser.data})
        else:
            stu = KeCheng.objects.filter(id=id).first()
            ser = KecSer(stu)
            return Response({'code': 200, 'list': ser.data})

    def post(self, request):
        ser = SUserSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})


class NianM(APIView):
    def get(self, request):
        id = request.GET.get('id')
        if not id:
            nian = NianJi.objects.all()
            ser = NianSer(nian, many=True)
            return Response({'code': 200, 'list': ser.data})
        else:
            nian = NianJi.objects.filter(id=id).first()
            ser = NianSer(nian)
            return Response({'code': 200, 'list': ser.data})

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = SUser.objects.filter(username=username).first()
        if username == user.username:
            if password == user.password:
                return Response({'code': 200, 'userid': user.id})
            else:
                return Response({'code': 20010, 'mes': '密码错误'})
        else:
            return Response({'code': 20011, 'mes': '账号错误'})


class SuserM(APIView):
    def get(self, request):
        id = request.GET.get('id')
        users = SUser.objects.filter(id=id).first()
        ser = SSUserSer(users)
        return Response({'code': 200, 'list': ser.data})
